package com.example.springboot.spring.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * 需要注册 Handler，并指定 URL
 * <p> 通过实现 WebSocketConfigurer 配置类，重写 registerWebSocketHandlers 方法，
 * <p> 注册自定义的 WebSocketHandler 的实现类 MyWebSocketHandler，并指定类对应的 websocket 访问的 ServerEndpoint 为 /webSocket。
 * <p> 通过 @EnableWebSocket 注解，启动 spring-boot-starter-websocket 的自动化配置
 * <p>
 *
 * @author Zhang.Z
 * @version 2025-09-21
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myWebSocketHandler(), "/webSocket")
                //添加拦截器
                .addInterceptors(new WebSocketInterceptor())
                //允许跨域
                .setAllowedOrigins("*");

        registry.addHandler(myWebSocketHandler(), "/sockjs/webSocket")
                .addInterceptors(new WebSocketInterceptor())
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Bean
    MyWebSocketHandler myWebSocketHandler() {
        return new MyWebSocketHandler();
    }
}
